import ticker
from download_tick_file import save_link
import os, time
from datetime import datetime
import inspect
import urllib.request
import re

class TickerRunner:
    def __init__(self):
        this_file = inspect.getfile(inspect.currentframe())
        self.dir_path = os.path.abspath(os.path.dirname(this_file))
        self.ticker = ticker.StockTicker(self.dir_path)
        self.task = {
            "stock_list": '',
            "download": ''
        }
        self.isAlive = True

    def start(self):
        print('系统运行中...')
        while self.isAlive:
            now = datetime.now()
            today_str = now.strftime('%Y%m%d')
            if today_str not in ['20180101', '20180215', '20180216', '20180219', '20180220', '20180221', '20180405', '20180406', '20180430', '20180501', '20180618', '20180924', '20181001', '20181002', '20181003', '20181003', '20181004', '20181005']:
                if now.weekday() < 5:
                    hms_int = int(now.strftime('%H%M%S'))
                    # 交易日9:00更新股票列表
                    if 90000 < hms_int and self.task.get("stock_list") != today_str:
                        self.task["stock_list"] = today_str
                        # 更新股票列表
                        self.ticker.update_stock_list()
                    if 91400 < hms_int < 113100 or 125900 < hms_int < 150600:
                        self.ticker.run_ticker()

                    if hms_int > 200000 and self.task.get("download") != today_str:
                        self.task["download"] = today_str
                        save_link(self.dir_path)
        time.sleep(2)

    def stop(self):
        print('系统停止运行...')
        self.isAlive = False


if __name__ == '__main__':
    TickerRunner().start()
